package utn.frba.matematicasuperior.utiles;

import javafx.geometry.Pos;
import javafx.scene.control.TableCell;
import javafx.scene.control.TextField;
import utn.frba.matematicasuperior.modelo.ParOrdenado;

public class CeldaEditableInteger extends TableCell<ParOrdenado, Integer> {

	private TextField textField;

	public CeldaEditableInteger() {
		this.setAlignment(Pos.CENTER);
	}

	@Override
	public void startEdit() {
		if (!isEmpty()) {
			super.startEdit();
			createTextField();
			setText(null);
			setGraphic(textField);
			textField.selectAll();
		}
	}

	@Override
	public void cancelEdit() {
		super.cancelEdit();

		setText(String.valueOf(getItem()));
		setGraphic(null);
	}

	@Override
	public void updateItem(Integer item, boolean empty) {
		super.updateItem(item, empty);
		if (this.getTableRow() != null && item != null) {
			setText(this.getTableRow().getIndex() + 1 + "");
		} else {
			setText("");
		}
	}

	private void createTextField() {
		textField = new TextField(getString());
		textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
	}

	private String getString() {
		return getItem() == null ? "" : getItem().toString();
	}
}
